<script setup lang="ts">
import {
  ref,
  reactive,
  computed,
  onMounted,
  onActivated,
  onDeactivated,
  getCurrentInstance
} from "vue";
// 以这种路径引入公共组件，可以解决volar提示v-slot:slotName slotName不存在的问题
import NavBar from "../../components/common/navbar/NavBar.vue";
// import NavBar from "components/common/navbar/NavBar.vue";
import HomeSwiper from "./childComps/HomeSwiper.vue";
import RecommendView from "./childComps/RecommendView.vue";
import FeatureView from "./childComps/FeatureView.vue";
import TabControl from "components/content/tabControl/TabControl.vue";
import GoodsList from "components/content/goods/GoodsList.vue";
import Scroll from "components/common/scroll/Scroll.vue";
import BackTop from "components/content/backTop/BackTop.vue";
import { requestHomeMultidata, requestHomeGoods } from "network/home.js";

// 变量
const titles: string[] = ["流行", "新款", "精选"];

const data = reactive({
  banners: [],
  recommends: [],
  goods: {
    pop: { page: 0, list: [] },
    new: { page: 0, list: [] },
    sell: { page: 0, list: [] },
  } as any,
});

const currentType = ref("pop");
let taboffSetTop = ref(0);
const isStayTop = ref(false);
const isShowBackTop = ref(false);
const saveY = 0;
const errors = {};

// 子组件对象
const tabControl1 = ref<any>(null);
const tabControl2 = ref<any>(null);
const scrollRef = ref<any>(null);

const showGoods = computed(() => {
  return data.goods[currentType.value].list;
});

/**
 * 网络请求相关
 */
async function getHomeMultidata() {
  await requestHomeMultidata().then((res: any) => {
    data.banners = res.data.banner.list;
    data.recommends = res.data.recommend.list;
  });
}

async function getHomeGoods(type: string) {
  const page = data.goods[type].page + 1;
  await requestHomeGoods(type, page).then((res: any) => {
    // 接口可用时调用方法
    if (res && res.data.list) data.goods[type].list.push(...res.data.list);
    data.goods[type].page += 1;
  });
}

// 事件
const tabClick = (index: number) => {
  switch (index) {
    case 0:
      currentType.value = "pop";
      break;
    case 1:
      currentType.value = "new";
      break;
    case 2:
      currentType.value = "sell";
      break;
  }
  tabControl1.value.currentIndex = index;
  tabControl2.value.currentIndex = index;
};
const scrollPostion = (position: any) => {
  // 判断backtop 是否显示
  // if ((-position.y) > 1000) isShowBackTop.value = true;
  // else isShowBackTop.value = false;
  // 一步搞定
  isShowBackTop.value = -position.y > 1000;

  // 判断tab-control 是否吸顶(fixed 定位)
  isStayTop.value = -position.y > taboffSetTop.value;
};

const backTop = () => {
  scrollRef.value.scrollTo(0, 0, 300);
};

const homeSwiperImageLoad = () => {
  // tab-control 的吸顶效果实现
  // 所有的组件都有一个属性$el:用于获取组件中的元素
  taboffSetTop.value = tabControl2.value.vDom.vel.offsetTop;
  // console.log(tabControl2.value.vDom.vel.offsetTop);
  // console.log(tabControl2.value.tabel.offsetTop);
};

const loadMore = async () => {
  // console.log("加载更多已完成", currentType.value);

  // 发送网络请求，请求更多的数据
  await getHomeGoods(currentType.value);
  scrollRef.value.finishPullUp();
  scrollRef.value.refresh();
  // console.log(scrollRef.value.scrollHeight);
};

onMounted(async () => {
  // 请求数据
  await getHomeGoods("new");
  await getHomeGoods("sell");
  await getHomeMultidata();
  await getHomeGoods("pop");

  // better-scroll bug 解决方案1
  // better-scroll 有个 scrollHeight 属性是计算了页面的可滚动高度的，但是有时候图片加载还未完成，这个高度已经计算出来了，
  // 所以需要在整个页面加载完成后 refresh下。让这个scrollHeigth刷新。加载多页数据后，也需要refresh，
  // 也可以通过监听图片加载完成后refresh 的方式，img.onload() || @load;
  // 课件里讲的是通过$bus事件总线的方式，但是其实没必要，在这里我是用的mounted函数里面refresh解决的better-scroll的这个bug

  scrollRef.value.refresh();
  // $toast.show('本网站仅用于效果展示，请不要在本页面及后续链接中下单支付任何商品！',3000);
});

// onActivated(() => {
//   $refs.scrollRef.scrollTo(0, saveY, 0);
//   $refs.scrollRef.refresh();
// });

// onDeactivated(() => {
//   saveY = $refs.scrollRef.getScrollY();

//   // 离开视图时，取消全局事件的监听
//   $bus.$off("itemImageLoad", itemImgListener);
// });
</script>

<template>
  <div class="home">
    <nav-bar>
      <template v-slot:nav-center>
        <div>购物街</div>
      </template>
    </nav-bar>

    <tab-control
      :titles="titles"
      @tabClick="tabClick"
      ref="tabControl1"
      :class="{ isStayTop }"
      v-show="isStayTop"
    ></tab-control>

    <scroll
      class="wrapper"
      ref="scrollRef"
      :probe-type="3"
      :pull-up-load="true"
      @scroll.passive="scrollPostion"
      @pullingUp.passive="loadMore"
    >
      <div class="content">
        <home-swiper
          :banners="data.banners"
          @swiperImageLoad="homeSwiperImageLoad"
        />
        <recommend-view :childRecommends="data.recommends" />
        <feature-view></feature-view>
        <tab-control
          :titles="['流行', '新款', '精选']"
          @tabClick="tabClick"
          ref="tabControl2"
        ></tab-control>
        <goods-list :childsGoods="showGoods"></goods-list>
      </div>
    </scroll>

    <BackTop @click.native="backTop" v-show="isShowBackTop"></BackTop>
  </div>
</template>

<style lang="less">
.home {
  height: 100vh;
  position: relative;

}


/* 吸顶效果 */
.isStayTop {
  position: relative;
  z-index: 6;
}

/* 方案一 */
/* .wrapper {
  height: calc(100% - 50px);
  overflow: hidden;
} */
.wrapper {
  position: absolute;
  top: 44px;
  bottom: 49px;
  left: 0;
  right: 0;
  overflow: hidden;
}
</style>
